#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <cstdio>
#include <cerrno>
#include <cstring>

using namespace std;

void SetNonBlock(int fd)
{
    int fl = fcntl(fd, F_GETFL);
    if(fl < 0)
    {
        perror("fcntl");
        return;
    }
    fcntl(fd, F_SETFL, fl | O_NONBLOCK);
    cout << "set " << fd << " to nonblock" << endl;
}

int main()
{
    char buffer[1024];
    SetNonBlock(0);
    sleep(1);
    while(true)
    {
        printf("Please Enter# ");
        fflush(stdout);

        ssize_t s = read(0, buffer, sizeof(buffer) - 1);
        if(s > 0)
        {
            buffer[s-1] = 0;
            cout << "echo@ " << buffer << endl;
        }
        else if(s == 0)
        {
            cout << "read done" << endl;
            break;
        }
        else
        {
            if(errno == EWOULDBLOCK)
            cerr << "read error, s = " << s << ", error node: " << errno << ", error str: " << strerror(errno) << endl;
            break;
        }
    }

    return 0;
}